package me.hyman.testcustomview.progressbar;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.util.AttributeSet;

import me.hyman.testcustomview.R;

/**
 * Created by luluteam on 2016/9/28.
 */
public class RoundProgressBarWithNumber extends HorizontalProgressBarWithNumber {

    private int mRadius = dp2px(30);
    private int mMaxPaintWidth;

    public RoundProgressBarWithNumber(Context context, AttributeSet attrs) {
        super(context, attrs);

        mReachedPBHeight = (int) (mUnReachedPBHeight * 2.5f);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.RoundProgressBarWithNumber);
        mRadius = (int) ta.getDimension(R.styleable.RoundProgressBarWithNumber_radius, mRadius);
        ta.recycle();

        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setStrokeCap(Paint.Cap.ROUND);
    }

    @Override
    protected synchronized void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        mMaxPaintWidth = Math.max(mReachedPBHeight, mUnReachedPBHeight);
        int except = mRadius * 2 + mMaxPaintWidth + getPaddingLeft() + getPaddingRight();
        int width = resolveSize(except, widthMeasureSpec);
        int height = resolveSize(except, heightMeasureSpec);
        int realWidth = Math.min(width, height);

        mRadius = (realWidth - getPaddingLeft() - getPaddingRight() - mMaxPaintWidth) / 2;

        setMeasuredDimension(realWidth, realWidth);
    }

    @Override
    protected synchronized void onDraw(Canvas canvas) {

        String text = getProgress() + "%";
        float textWidth = mPaint.measureText(text);
        float textHeight = (mPaint.descent() + mPaint.ascent()) / 2;

        canvas.save();
        canvas.translate(getPaddingLeft() + mMaxPaintWidth / 2, getPaddingTop() + mMaxPaintWidth /2);

        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setColor(mUnReachedPBColor);
        mPaint.setStrokeWidth(mUnReachedPBHeight);
        canvas.drawCircle(mRadius, mRadius, mRadius, mPaint);

        mPaint.setColor(mReachedPBColor);
        mPaint.setStrokeWidth(mReachedPBHeight);
        float sweepAngle = getProgress() * 1.0f / getMax() * 360;
        //canvas.drawArc(new RectF(0, 0, mRadius*2, mRadius*2), 0, sweepAngle, false, mPaint);
        canvas.drawArc(new RectF(0, 0, mRadius*2, mRadius*2), -90, sweepAngle, false, mPaint);

        mPaint.setStyle(Paint.Style.FILL);
        canvas.drawText(text, mRadius - textWidth/2, mRadius - textHeight, mPaint);

        canvas.restore();
    }
}
